package com.uyuni.rpc.registry;

import com.uyuni.rpc.transport.ConnectionUtils;
import com.uyuni.rpc.transport.model.NettyRequestProcessor;
import com.uyuni.rpc.transport.model.RemotingTransporter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.uyuni.rpc.common.protocol.UyuniProtocol.*;

/**
 * 注册中心默认处理器
 */
public class DefaultRegistryProcessor implements NettyRequestProcessor {

    private static final Logger logger = LoggerFactory.getLogger(DefaultRegistryProcessor.class);

    private DefaultRegistryServer defaultRegistryServer;

    public DefaultRegistryProcessor(DefaultRegistryServer defaultRegistryServer) {
        this.defaultRegistryServer = defaultRegistryServer;
    }

    /**
     * 注册中心作为服务端处理不同客户端发送过来的请求
     * @param ctx
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public RemotingTransporter processRequest(ChannelHandlerContext ctx, RemotingTransporter request) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("receive request, {} {} {}",//
                    request.getCode(), //
                    ConnectionUtils.parseChannelRemoteAddr(ctx.channel()), //
                    request);
        }
        switch (request.getCode()) {
            case PUBLISH_SERVICE: // 处理服务提供者provider推送的服务信息
                return this.defaultRegistryServer.getRegistryProviderManager().handlerRegister(request, ctx.channel()); // 要保持幂等性，同一个实例重复发布同一个服务的时候对于注册中心来说是无影响的
            case PUBLISH_CANCEL_SERVICE: // 处理服务提供者provider推送的服务取消的信息
                return this.defaultRegistryServer.getRegistryProviderManager().handlerRegisterCancel(request, ctx.channel());
            case SUBSCRIBE_SERVICE: // 处理服务消费者consumer订阅服务的请求
                return this.defaultRegistryServer.getRegistryProviderManager().handleSubscribe(request, ctx.channel());
            case MANAGER_SERVICE: // 处理管理者发送过来的服务管理服务
                return this.defaultRegistryServer.getRegistryProviderManager().handleManager(request, ctx.channel());
        }
        return null;
    }


    /***********Getter and Setter*************/

    public DefaultRegistryServer getDefaultRegistryServer() {
        return defaultRegistryServer;
    }

    public void setDefaultRegistryServer(DefaultRegistryServer defaultRegistryServer) {
        this.defaultRegistryServer = defaultRegistryServer;
    }

}
